/**
 * 
 * @date 201912  LIFENG271
 * @Description: PC端指南针数据采集，依赖jQuery库
 */

(function (window, undefined) {
    var bury = function () {
        var self = this;
        self.init();
        if (document.body.addEventListener) {
            document.body.addEventListener("click", function (e) {
                if( window._isStatic ){return}//核保成功页面，静态调用不需要使用绑定事件方法
                if( !jQuery && !_common ) throw "缺少依赖文件";
                findPoint(e, buryObj);
            }, true)//使用事件捕获

        } else {//支持更早ie浏览器
            document.body.attachEvent("click", function (e) {//detachEvent移除事件
                if( window._isStatic ){return}//核保成功页面，静态调用不需要使用绑定事件方法
                if( !jQuery && !_common ) throw "缺少依赖文件";
                findPoint(e, buryObj);
            })
        }
    }

    // 自定义事件的公共属性
    var commonAttributes = {
        productPage: "产品页",
        productName: window.gProductName || "", // 产品名称
        ProductCode: window.gProductCode || "", // 产品代码
        PageLevel: "PC_1",
        PartnerID: "", // 合作伙伴
        media_source: "", // 媒体来源
        Platform_source: "PC",//PC和mobile
        inner_media:"",
        inner_entry:""
    };

    if (!commonAttributes.media_source) {
        commonAttributes.media_source = _getParams("WT.mc_id") || _getParams('mediaSource') || "";
        commonAttributes.PartnerID= _getParams("PartnerID")||_getParams("PartnerId")|| "";
    }

    // 自定义事件及属性
    var buryObj = null;
    var domArr = [
        {
            "selector": "#T-ljgm-zjly",
            "eventId": "NST_H00053688",
            "attributes": {
                "title": "产品页-立即投保"
            }
        }
    ]
    if (commonAttributes.ProductCode == "P030001") {
        domArr = [
            {
                "selector": "#fixeNavSubmit",
                "eventId": "NST_H00053688",
                "attributes": {
                    "title": "产品页-立即投保"
                }
            },
            {
                "selector": "#T-ljgm-zjly",
                "eventId": "NST_H00053688",
                "attributes": {
                    "title": "产品页-立即投保"
                }
            }
        ]
    }
    if (commonAttributes.ProductCode == "P060006") {
        domArr = [
            {
                "selector": "#T-ljgm01",
                "eventId": "NST_H00053688",
                "attributes": {
                    "title": "产品页-立即投保"
                }
            },
            {
                "selector": "#page_Tab_buy",
                "eventId": "NST_H00053688",
                "attributes": {
                    "title": "产品页-立即投保"
                }
            }
        ]
    }
    // var domArr = [
        
    //     {
    //         "selector": ".page_Tab_nav li:nth-child(1)",
    //         "eventId": "NST_H00042181",
    //         "attributes": {
    //             "title": "保障计划(上)",
                
    //         }
    //     },
    //     {
    //         "selector": ".page_Tab_nav li:nth-child(2)",
    //         "eventId": "NST_H00042184",
    //         "attributes": {
    //             "title": "产品特色"
    //         }
    //     },
    //     {
    //         "selector": ".page_Tab_nav li:nth-child(3)",
    //         "eventId": "NST_H00042185",
    //         "attributes": {
    //             "title": "投保须知"
    //         }
    //     },
    //     {
    //         "selector": ".page_Tab_nav li:nth-child(4)",
    //         "eventId": "NST_H00042188",
    //         "attributes": {
    //             "title": "常见问题"
    //         }
    //     },
    //     {
    //         "selector": ".bdyl a",
    //         "eventId": "NST_H00042186",
    //         "attributes": {
    //             "title": "保单预览"
    //         }
    //     },
    //     {
    //         "selector": ".zytx a",
    //         "eventId": "NST_H00042187",
    //         "attributes": {
    //             "title": "重要提醒"
    //         }
    //     },
    //     {
    //         "selector": "#T-ljgm-zjly",
    //         "eventId": "NST_H00042178",
    //         "attributes": {
    //             "title": "立即投保"
    //         }
    //     },
    //     {
    //         "selector": ".bzjh_btn",
    //         "eventId": "NST_H00042182",
    //         "attributes": {
    //             "title": "保障计划(下)"
    //         }
    //     },
    //     {
    //         "selector": ".bzxqjd_btn",
    //         "eventId": "NST_H00042183",
    //         "attributes": {
    //             "title": "保障详情解读"
    //         }
    //     },
    //     {
    //         "selector": "#T-jwysytkxw01",
    //         "eventId": "NST_H00042179",
    //         "attributes": {
    //             "title": "保险条款（上）"
    //         }
    //     },
    //     {
    //         "selector": "#T-jwysytkxw02",
    //         "eventId": "NST_H00042180",
    //         "attributes": {
    //             "title": "保险条款（下）"
    //         }
    //     },
        
    //     {
    //         "selector": "#zyflb",
    //         "eventId": "NST_H00042192",
    //         "attributes": {
    //             "title": "职业分类表"
    //         }
    //     },
    //     {
    //         "selector": "#T-zyflb",
    //         "eventId": "NST_H00042192",
    //         "attributes": {
    //             "title": "查看职业分类表"
    //         }
    //     }
        
        

    // ];

    window._buryBackUpData = {};
    window._paySuccessBuryData = function () {//核保成功时候增加一个埋点
        var data = window._buryBackUpData["NST_H010014"]//拿到立即支付的埋点数据
        var obj = { attributes: {} };
        var eventId = "NST_H010020";//核保成功埋点id
        obj.attributes = data;
        obj.attributes.title = "核保成功";
        window.dtTracker('customerTrack', eventId, JSON.stringify(obj));
    }

    window._applySuccessBuryData = function (acceptanceResult,policyNo) {//承保成功时候增加一个埋点
        var obj = { attributes: {} };
        var eventId = "NST_H010023";//核保成功埋点id
        obj.attributes.title = "承保结果";
        obj.attributes.mediaSource=gUrlData["mediaSource"]||"";
        obj.attributes.acceptanceResult=acceptanceResult;
        obj.attributes.partnerID=gUrlData["partnerID"]||"";
        obj.attributes.isWechart="PC";
        obj.attributes.productCode="P020082";
        obj.attributes.policyNo=policyNo;//保单号
        window.dtTracker('customerTrack', eventId, JSON.stringify(obj));
    }

    function _getParams(name) {

	    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	    var r = window.location.search.substr(1).match(reg);
	    if(r) {
	        return decodeURI(r[2]).replace(/</g, "&lt;").replace(/>/g, "&gt;");
	    }
	    return null;
	}


    function findPoint(e, buryObj) {
        if (!commonAttributes.media_source) {
            commonAttributes.media_source = _getParams("WT.mc_id") || _getParams('mediaSource') || "";
            commonAttributes.PartnerID= _getParams("PartnerID")||_getParams("PartnerId")|| "";
       }
        var className = "";
        var $e = $(e.target);
        var id = $e.attr("id");
        var selector = "";
        

        if (!buryObj) return;
        if ($e.hasClass("ch") && $e.parents("#question-area-wrap").size()) {//常见问题,报价页和信息填写页判断
            if ($e.parent().parent().hasClass("quote-question")) {
                className = "quote-question";
            } else if ($e.parent().parent().hasClass("supplement-question")) {
                className = "supplement-question";
            }
            $e.addClass(className);
        }

        for (var i = 0; i < domArr.length; i++) {
            var eventId = domArr[i]["eventId"];
            var attributes = domArr[i]["attributes"];
                selector = domArr[i]["selector"];

            if (selector.indexOf(".") > -1) className = selector.replace(".", "");
            if (selector.indexOf(" a") > -1) className = selector.replace(".", "").replace(" a", ""); //保单预览，重要提醒
            if (selector == "#nextBtn") {
                attributes["insurantNo"] = $("#insurantNum").val();
            }
            if ("#" + id == "#supplement-btn-next") {
                //Female Male
                var $applicantForm = $("#applicant-form");
                attributes["applicantSex"] = $applicantForm.find("[name=sex]:checked").val();
                attributes["applicantAge"] = _common.date.getFullAge($("#user-birth").val(), _common.strServerDate);
                attributes["insurantAge"]  = _common.date.getFullAge($("#ins_birth_0").val(), _common.strServerDate);
                attributes["insurantSex"]  = $("#ins_sex_m_0,#ins_sex_f_0").filter(":checked").val();
                attributes["isAtuoRewal"]  = $("#renewal_Flag").is(":checked") ? "Y" : "N";
                attributes["isPolicy"] = $("#i_Flag").is(":checked") ? "Y" : "N";
                $.extend(attributes, commonAttributes);
                window._buryBackUpData["NST_H010014"] = attributes//核保的时候使用
                buryObj.point(eventId, attributes);
                break;
            }

            if (eventId && selector == "#" + id) {
                $.extend(attributes, commonAttributes);
                buryObj.point(eventId, attributes);
                break;
            }

            if (eventId && className && $e.hasClass(className)) {
                $.extend(attributes, commonAttributes);
                buryObj.point(eventId, attributes);
                break;
            }

            if (eventId && className && $e.index()==i && $e.parent().hasClass("page_Tab_nav")) {
                $.extend(attributes, commonAttributes);
                buryObj.point(eventId, attributes);
                break;
            }

            if (eventId && className &&i>3 && $e.parent().hasClass(className)) { //保单预览，重要提醒
                $.extend(attributes, commonAttributes);
                buryObj.point(eventId, attributes);
                break;
            }

        }
    }

    bury.prototype = {
        isPro: function () {
            // var pro = !(window.location.hostname.indexOf("stg")>-1);
            // return pro;

            var l = window.location.href;
            var pro = l.indexOf('baoxian.pingan.com')==-1 ? false:true;
            return pro;
        },
        init: function () {
            var defaultOptions = {
                test: {
                    trackApiUrl: 'https://test1-ant.pingan.com.cn/c.gif',
                    trackerJsUrl: 'https://test1-ant.pingan.com.cn/tracker.min.js',
                    siteId: 'ppey3cmtP6ijpMSh',
                    projectId: 't2I0BWhoVxMI8aKM'
                },
                pro: {
                    trackApiUrl: 'https://ant.pingan.com.cn/c.gif',
                    trackerJsUrl: 'https://ant.pingan.com.cn/tracker.min.js',
                    siteId: 'WM6btUqWZviBdsyE',
                    projectId: '09SJZ3rJxQPKiRi1'
                }
            };
            // 判断是否生产环境域名
            var params = this.isPro() ? defaultOptions['pro'] : defaultOptions['test'];

            var siteId = params.siteId;
            var projectId = params.projectId;

            // 加载上报平台sdk
            window.dtTracker = window.dtTracker || function () { (dtTracker.q = dtTracker.q || []).push(arguments) };
            dtTracker.l = +new Date;
            dtTracker('setTrackApiUrl', params.trackApiUrl); // 生产环境：https://ant.pingan.com.cn/c.gif
            dtTracker('setSiteId', siteId);
            //dtTracker('setOSiteId', 'xxx');//接入数据云1.0才需要设置
            dtTracker('setProjectId', projectId);
            //登录或注册成功时cookie或local中有userid，则需设置userID；没有则不设置
            //dtTracker('setUserId', 'xxxx');
            dtTracker('pageview');      
            dtTracker('customerTrack', 'NST_H00053684', JSON.stringify(commonAttributes));


            (function () {
                var d = document,
                    g = d.createElement('script'),
                    s = d.getElementsByTagName('script')[0];
                g.type = 'text/javascript';
                g.async = true;
                g.defer = true;
                g.src = params.trackerJsUrl;
                s.parentNode.insertBefore(g, s)
            })();
        },
        point: function (eventId, obj) {
            window.dtTracker('customerTrack', eventId, JSON.stringify(obj));
        }
    }

    window['bury'] = bury;
    buryObj = new bury();
   
})(window, undefined)
